import type { CustomRequestOptions } from '@/utils/http/requestInterceptor';
import { ResultCodeEnum } from '@/enums';
import { refreshToken } from '@/api/user';
import { useUserStore } from '@/store';
import { http } from '@/utils/http';
import { clearAndRedirect } from '@/utils/common';

type TQueue = {
  config: CustomRequestOptions;
  resolve: Function;
};

export const useRefreshToken = async (
  resolve: Function,
  options: CustomRequestOptions
) => {
  let refreshing = false;
  let queue: TQueue[] = [];
  console.log('打印***1', 1);
  queue.push({
    config: options,
    resolve
  });
  if (refreshing) {
    return;
  }
  // 401错误  -> 刷新token，清理用户信息，跳转到登录页
  refreshing = true;
  const { code, data } = await refreshToken({
    refreshToken: useUserStore().userInfo.refreshToken
  });
  refreshing = false;
  if (code === ResultCodeEnum.SUCCESS) {
    useUserStore().setUserInfo({
      ...useUserStore().userInfo,
      accessToken: data.accessToken,
      refreshToken: data.refreshToken
    });

    try {
      queue.forEach((queueItem) => {
        queueItem.resolve(http(queueItem.config));
      });
      queue = [];
    } catch (error) {
      console.log('打印***error', error);
      queue = [];
    }
  } else {
    clearAndRedirect();
  }
};

export const useHttpResolve = async <T>(
  res: UniApp.RequestSuccessCallbackResult,
  resolve: Function,
  options: CustomRequestOptions
) => {
  console.log('打印***res', res);
  if (res.statusCode >= 200 && res.statusCode < 300) {
    resolve(res.data as IResData<T>);
  } else if (res.statusCode === 401 && !options.url.includes('refreshToken')) {
    useRefreshToken(resolve, options);
    resolve({ code: 1, data: res as any, message: '请求错误' });
  } else if (res.statusCode === 401) {
    clearAndRedirect();
  } else if (res.statusCode === 403) {
    uni.showToast({
      icon: 'none',
      title: '登录已失效，请重新登录'
    });
    clearAndRedirect();
    resolve({
      code: 1,
      data: res as any,
      message: '请求错误'
    });
  } else {
    uni.showToast({
      icon: 'none',
      title: (res.data as IResData<T>).message || '请求错误'
    });
    resolve({
      code: 1,
      data: res as any,
      message: '请求错误'
    });
  }
};

export const useHttpFail = (
  resolve: Function,
  err: UniApp.GeneralCallbackResult
) => {
  console.log('打印***err', err);
  uni.showToast({
    icon: 'none',
    title: '网络错误，换个网络试试'
  });
  resolve({
    code: 1,
    data: err as any,
    message: '网络错误，换个网络试试'
  });
};
